﻿---------------------------------------------------------------------------------------------------

CREATE PROCEDURE [Kernel].[SaveAddress]
@OID					bigint			= NULL,
@Version				rowversion		= NULL,
@Address1				varchar(128)	= NULL,
@Address2				varchar(128)	= NULL,
@City					varchar(128)	= NULL,
@State					varchar(128)	= NULL,
@Postalcode				varchar(30)		= NULL,
@Country				varchar(128)	= NULL

AS 

---------------------------------------------------------------------------------------------------
--						Liberty
---------------------------------------------------------------------------------------------------
--  Stored Procedure :: SaveAddress
--                                                                            
---------------------------------------------------------------------------------------------------

SET NOCOUNT ON 

DECLARE @newOID bigint


---------------------------------------------------------------------------------------------------
-- Step 1: "Save" the Address
---------------------------------------------------------------------------------------------------
-- If no OID was passed in, this is a new row; perform an insert.
IF ISNULL(@OID, 0) <= 0
BEGIN
	INSERT INTO dbo.Addresses
	(Address1, Address2, City, State, PostalCode, Country, UpdatedDate, CreatedDate)
	VALUES
	(@Address1, @Address2, @City, @State, @PostalCode, @Country, GETDATE(), GETDATE())

	SET @OID =  SCOPE_IDENTITY()

	-- Retutn OID and timestamp of newly inserted object
	SELECT @Version = Version 
	FROM dbo.Addresses 
	WHERE OID = @OID
END

-- If OID was passed in, perform an update
ELSE
BEGIN
	-- Attempt updating object (using both OID and timestamp for concurrency reasons)
	UPDATE dbo.Addresses
	SET Address1 = @Address1
		,Address2 = @Address2
		,City = @City
		,State = @State
		,PostalCode = @PostalCode
		,Country = @Country
		,UpdatedDate = GETDATE()
	WHERE (OID = @OID) 
	AND (Version = @Version)

	-- If no records were found (and updated) - it means that another process had updated 
	-- this record (therefore timestamp will be different) or record was deleted (OID not found)
	-- Either way, we need to raise exception
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR(99999, 16, 1, 'Address')
	END

	-- Record was found - return OID and new timestamp
	ELSE
	BEGIN 
		SELECT @Version = Version 
		FROM dbo.Addresses 
		WHERE OID = @OID
	END
END


---------------------------------------------------------------------------------------------------
-- Step 2: Return all the associated values to the caller.
---------------------------------------------------------------------------------------------------

SELECT @OID as 'OID', @Version as 'Version'


RETURN(0)


